import axios from 'axios';
import { ElMessage, ElMessageBox,ElLoading } from 'element-plus';
import { Session } from '../utils/storage';


declare module 'axios' {
	interface AxiosInstance {
		(config: AxiosRequestConfig): Promise<any>
	}
}
// 配置新建一个 axios 实例
	const service = axios.create({
		baseURL: import.meta.env.VITE_API_URL as any,
		timeout: 50000,
		headers: {'Content-Type': 'application/json'},
	});
	let loading: any;
// 添加请求拦截器
                       //@ts-ignore
	service.interceptors.request.use(
		(config) => {
			loading = ElLoading.service({
				lock: false,
				text: '正在请求数据....',
				background: 'rgba(0, 0, 0, 0.3)',
			});
			// 在发送请求之前做些什么 token
			if (Session.get('token')) {
				(<any>config.headers).common['Authorization'] = `Bearer ${Session.get('token')}`;
				// config.headers.common['Authorization'] = `${Session.get('token')}`;
			}
			return config;
		},
		(error) => {
			// 对请求错误做些什么
			return Promise.reject(error);
		}
	);

// 添加响应拦截器
	service.interceptors.response.use(
		(response) => {
			loading?.close();
			// 对响应数据做点什么
			const res = response.data;
			if (res.code && res.code !== 0) {
				// `token` 过期或者账号已在别处登录
				if (res.code === 401 || res.code === 4001) {
					Session.clear(); // 清除浏览器全部临时缓存
					// window.location.href = '/'; // 去登录页
					ElMessage.error(res.msg);
					return Promise.reject(service.interceptors.response);
				} else if (+res.code === 400 || +res.code === 500 || +res.code === -1) {
					ElMessage.error(res.msg || '请检查参数是否正确');
				}
				return response.data;
			} else {
				return response.data;
			}
		},
		(error) => {
			if (error.message.indexOf('timeout') != -1) {
				ElMessage.error('网络超时');
			} else if (error.message == 'Network Error') {
				ElMessage.error('网络连接错误');
			} else {
				if (error.response.data) ElMessage.error(error.response.statusText);
				else ElMessage.error('接口路径找不到');
			}
			return Promise.reject(error);
		}
	);
export default service;
